package jiangnan

import ( 
	"strings"
	"io/ioutil"
	"bytes"
	"fmt"
    "encoding/xml"
    "golang.org/x/text/encoding/simplifiedchinese"
    "golang.org/x/text/transform"
) 

type Result struct {
    Msg []Msg `xml:"MSG"`
}

type Msg struct {
    Agenflow   string    `xml:"agenflow"`
    Bustype    string    `xml:"bustype"`
    Bussubtype string    `xml:"bussubtype"`
    Rspcode    string    `xml:"rspcode"`
}

func (msg *Msg) ChkisReq() (flag bool) {
    if msg.Rspcode == "" {
        flag = true
    }else{
        flag = false
    }
    return flag
}


func ParseJiangNan(input []byte) map[string]interface{} {

    tmpstr:=strings.Replace(strings.Replace(string(input)," encoding='GB18030'","",1)," encoding=\"GB18030\"","",1)
    tmpstr=strings.Replace(strings.Replace(tmpstr," encoding='GB2312'","",1)," encoding=\"GB2312\"","",1)

    trstr,err:=Gb18030ToUtf8([]byte(tmpstr))
    if err!=nil{
        fmt.Println(err)
    }
    var result Result
    err = xml.Unmarshal([]byte(trstr), &result)
    // fmt.Println(result)
    if err != nil {
        fmt.Println(err)
    }
    info := map[string]interface{}{
        "tranCode":result.Msg[0].Bustype+result.Msg[0].Bussubtype,
		"agenflow":result.Msg[0].Agenflow,
		"rspcode":result.Msg[0].Rspcode,
    }
    // fmt.Println(info)
    return info
}


func Gb18030ToUtf8(s []byte)([]byte,error){
    reader := transform.NewReader(bytes.NewReader(s),simplifiedchinese.GB18030.NewDecoder())
    d,e := ioutil.ReadAll(reader)
    if e!=nil{
        return nil,e
    }
    return d ,nil
}

